package cn.sportvip.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

public class JsonHandlerExceptionResolver extends
		AbstractHandlerExceptionResolver {

	private static final Logger LOGGER = LoggerFactory.getLogger(JsonHandlerExceptionResolver.class);
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String uri = request.getRequestURI();
		
		@SuppressWarnings("unchecked")
		Map<Object, Object[]> params = request.getParameterMap();
		StringBuilder paramsStr = new StringBuilder();
		for(Object key:params.keySet()){
			paramsStr.append(key).append("=").append(params.get(key)[0].toString()).append(",");
		}
		
		LOGGER.error("请求：{}@{}发生异常!", paramsStr.toString(), uri);
		LOGGER.error(ex.getMessage(), ex);
		
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		ServletOutputStream os = null;
		try {
			os = response.getOutputStream();
		} catch (IOException e) {
			LOGGER.error("getOutputStreamError!", e);
		}
		PrintWriter pw = new PrintWriter(os);
		if(ex instanceof GeneralException){
			pw.write(String.format("{\"errorCode\":"+((GeneralException) ex).getErrorCode()+",\"exception\":\"%s\",\"msg\":\"%s\"}", ex.getClass().getSimpleName(),ex.getMessage()));
		}else{
			pw.write(String.format("{\"errorCode\":-1,\"exception\":\"%s\",\"msg\":\"%s\"}", ex.getClass().getSimpleName(),ex.getMessage()));
		}
		pw.flush();
		return null;
	}

}
